package main

import (
	"context"
	"fmt"

	"io"
	"os"
	"os/exec"
	"strings"

	"time"
)

//通过管道同步获取日志的函数
func syncLog(reader io.ReadCloser) {
	f, _ := os.OpenFile("file.log", os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
	defer f.Close()
	buf := make([]byte, 1024, 1024)
	for {
		strNum, err := reader.Read(buf)
		if strNum > 0 {
			outputByte := buf[:strNum]
			f.WriteString(string(outputByte))

			fmt.Println(string(outputByte))
		}
		if err != nil {
			//读到结尾
			if err == io.EOF || strings.Contains(err.Error(), "file already closed") {
				err = nil
			}
		}
	}
}

var cmdStdoutPipe io.ReadCloser
var cmdStderrPipe io.ReadCloser
var err error

func query()  {
	cmdStr := `
#!/bin/bash
cd /Volumes/E/www/go/src/hello/
go run main.go
`
	cmd := exec.Command("bash", "-c", cmdStr)
	//这里得到标准输出和标准错误输出的两个管道，此处获取了错误处理
	cmdStdoutPipe, err = cmd.StdoutPipe()
	cmdStderrPipe, err = cmd.StderrPipe()
	err := cmd.Start()
	if err != nil {
		fmt.Println(err)
	}
	go syncLog(cmdStdoutPipe)
	go syncLog(cmdStderrPipe)



	err = cmd.Wait()

	if err != nil {
		fmt.Println(err)
	}
}

func main() {
	//定义一个每秒1次输出的shell


	ctx, _ := context.WithCancel(context.Background())
	cmd := exec.CommandContext(ctx, "./b")

	cmd.Stdout = os.Stdout
	cmd.Start()

	time.Sleep(2 * time.Second)
	fmt.Println("退出程序中...", cmd.Process.Pid)
	//cancel()

	cmd.Wait()
	//for{
	//	query()
	//	fmt.Println("=====等个10秒钟=====")
	//	php2go.Sleep(10)
	//	err=cmdStdoutPipe.Close()
	//	err=cmdStderrPipe.Close()
	//}


}
